package org.dromara.system.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.DeviceDetail;
import org.dromara.system.domain.TResponse;
import org.dromara.system.mapper.DeviceDetailMapper;
import org.dromara.system.mapper.TResponseMapper;
import org.dromara.web.utils.QRCodeDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.TResponseVo;
import org.dromara.system.domain.bo.TResponseBo;
import org.dromara.system.service.ITResponseService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 问卷收集
 *
 * @author Lion Li
 * @date 2024-10-27
 */
@Validated
@RequiredArgsConstructor
@RestController
@Slf4j
@RequestMapping("/system/response")
public class TResponseController extends BaseController {

    private final ITResponseService tResponseService;


    @Autowired
    private TResponseMapper tResponseMapper;

    @Autowired
    private DeviceDetailMapper deviceDetailMapper;


    @PostMapping("/getTextAndVerify")
    @SaIgnore
    public R<DeviceDetail> getTextAndVerify(@RequestBody Map<String, String> text) {
        String textStr = text.get("text");
        if (textStr == null || textStr.isEmpty()) {
            return R.warn("text不能为空");
        }
        DeviceDetail deviceId = deviceDetailMapper.selectOne(new QueryWrapper<DeviceDetail>().eq("connect", textStr));
        if (deviceId == null) {
            return R.warn("设备不存在");
        } else {
            return R.ok(deviceId);
        }

    }

    @PostMapping("/refresh")
    @SaIgnore
    public R<DeviceDetail> refresh(@RequestBody Map<String, String> bindDevice) {
        String textStr = bindDevice.get("text");
        String deviceNumber = bindDevice.get("unitNumber");
        String address = bindDevice.get("address");
        if (textStr == null || textStr.isEmpty() || deviceNumber == null || deviceNumber.isEmpty() || address == null || address.isEmpty()) {
            return R.fail("参数不能为空");
        }
        DeviceDetail deviceId = deviceDetailMapper.selectOne(new QueryWrapper<DeviceDetail>().eq("connect", textStr));
        if (deviceId != null) {
            deviceId.setUnitNumber(deviceNumber);
            deviceId.setChargingMedium(address);
            deviceDetailMapper.updateById(deviceId);
            return R.ok(deviceId);
        } else {
            return R.fail("设备不存在");
        }
    }


    @PostMapping("/bindDevice")
    @SaIgnore
    public R<DeviceDetail> bindDevice(@RequestBody Map<String, String> bindDevice) {
        String textStr = bindDevice.get("text");
        String deviceNumber = bindDevice.get("unitNumber");
        String address = bindDevice.get("address");
        if (textStr == null || textStr.isEmpty() || deviceNumber == null || deviceNumber.isEmpty() || address == null || address.isEmpty()) {
            return R.fail("参数不能为空");
        }
        DeviceDetail deviceId = deviceDetailMapper.selectOne(new QueryWrapper<DeviceDetail>().eq("connect", textStr));
        if (deviceId == null) {
            List<DeviceDetail> deviceDetail = deviceDetailMapper.selectList(new QueryWrapper<DeviceDetail>().eq("product_number", deviceNumber));
            if (deviceDetail.size() == 1 && (deviceDetail.get(0).getConnect() == null || deviceDetail.get(0).getConnect().isEmpty())) {
                deviceDetail.get(0).setConnect(textStr);
                deviceDetail.get(0).setChargingMedium(address);
                deviceDetailMapper.updateById(deviceDetail.get(0));
                return R.ok(deviceDetail.get(0));
            } else {
                return R.fail("设备不存在或已绑定");
            }

        } else {
            return R.fail("设备已绑定");
        }

    }


    @GetMapping("/scan")
    @SaIgnore
    public R<Object> scan(@RequestParam("qrCodeUrl") String qrCodeUrl) {
        String decodedText = QRCodeDecoder.decodeQRCodeFromURL(qrCodeUrl);
        if (decodedText != null) {
            String codeUrl = decodedText;
            log.info("codeUrl: " + codeUrl);

            if (codeUrl.contains("cylinder")) { //永安钢瓶
                String number = codeUrl.split("=")[1];
                String url = "https://cylinder.lnyagp.com/api/bizProductArchives/getlist?qrcodeNumber=" + number + "&delFlag=0&orderBy=create_time%20desc";
                String response = HttpUtil.get(url);
                JSONObject jsonObject = JSONUtil.parseObj(response);
                JSONArray items = jsonObject.getJSONArray("items");
                if (items.size() > 0) {
                    JSONObject item = items.getJSONObject(0);
                    return R.ok(item);

                }
            }
        } else {
            return R.fail("无法解析二维码。");
        }

        return R.ok();
    }

    @PostMapping("/upload")
    public R<Integer> upload(@RequestBody TResponseBo tResponseBo) {

        TResponse tResponse = new TResponse();
        tResponse.setSurveyId(tResponseBo.getSurveyId());
        tResponse.setUserId(tResponseBo.getUserId());
        tResponse.setResponseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        tResponse.setTenantId(StpUtil.getLoginDevice());
        tResponse.setResponseContent(tResponseBo.getResponseContent());

        return R.ok(tResponseMapper.insert(tResponse));
    }

    /**
     * 查询问卷收集列表
     */
    @SaCheckPermission("system:response:list")
    @GetMapping("/list")
    public TableDataInfo<TResponseVo> list(TResponseBo bo, PageQuery pageQuery) {
        return tResponseService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出问卷收集列表
     */
    @SaCheckPermission("system:response:export")
    @Log(title = "问卷收集", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TResponseBo bo, HttpServletResponse response) {
        List<TResponseVo> list = tResponseService.queryList(bo);
        ExcelUtil.exportExcel(list, "问卷收集", TResponseVo.class, response);
    }

    /**
     * 获取问卷收集详细信息
     *
     * @param responseId 主键
     */
    @SaCheckPermission("system:response:query")
    @GetMapping("/{responseId}")
    public R<TResponseVo> getInfo(@NotNull(message = "主键不能为空")
                                  @PathVariable Integer responseId) {
        return R.ok(tResponseService.queryById(responseId));
    }

    /**
     * 新增问卷收集
     */
    @SaCheckPermission("system:response:add")
    @Log(title = "问卷收集", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TResponseBo bo) {
        return toAjax(tResponseService.insertByBo(bo));
    }

    /**
     * 修改问卷收集
     */
    @SaCheckPermission("system:response:edit")
    @Log(title = "问卷收集", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TResponseBo bo) {
        return toAjax(tResponseService.updateByBo(bo));
    }

    /**
     * 删除问卷收集
     *
     * @param responseIds 主键串
     */
    @SaCheckPermission("system:response:remove")
    @Log(title = "问卷收集", businessType = BusinessType.DELETE)
    @DeleteMapping("/{responseIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Integer[] responseIds) {
        return toAjax(tResponseService.deleteWithValidByIds(List.of(responseIds), true));
    }
}
